import * as Blockly from 'blockly/core'
Blockly.Blocks['promise_create'] = {
  init: function () {
    var validatorAwait = function (newValue) {
      var sourceBlock = this.getSourceBlock()
      sourceBlock.useAwait = newValue === 'TRUE'
      sourceBlock.updateBlock()
    }
    const field = new Blockly.FieldCheckbox('TRUE')
    field.setValidator(validatorAwait)
    this.setColour(160)
    this.appendDummyInput('REQUEST')
      .appendField('Promise对象  使用await')
      .appendField(field, 'AWAIT')
      .appendField(' 参数(resolve, reject)')
    this.appendStatementInput('FUNCBODY')
    this.setPreviousStatement(true, null)
    this.setNextStatement(true, null)
  },
  updateBlock: function () {
    if (!this.useAwait) {
      this.setPreviousStatement(false)
      this.setNextStatement(false)
      this.setOutput(true, null)
    } else {
      this.setOutput(false, null)
      this.setPreviousStatement(true)
      this.setNextStatement(true)
    }
  }
}

Blockly.JavaScript['promise_create'] = function (block) {
  const useAwait = block.useAwait
  console.log('useAwait', useAwait)
  let code = `new Promise((resolve,reject)=>{\n`
  if (useAwait) {
    code = `await ${code}`
  }
  const body = Blockly.JavaScript.statementToCode(block, 'FUNCBODY')
  code = `${code}${body}\n})\n`
  return code
}

// 2 -----------resolve传参-----------------
Blockly.Blocks['resolve'] = {
  init: function () {
    this.setColour(160)
    this.appendValueInput('RESOLVE')
      .appendField('relove返回')
    this.setPreviousStatement(true, null)
    this.setNextStatement(true, null)
    this.setInputsInline(false)
  }
}

Blockly.JavaScript['resolve'] = function (block) {
  var value = Blockly.JavaScript.valueToCode(
    block,
    'RESOLVE',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  )

  return `resolve(${value})\n`
}

// 3 -----------reject传参-----------------
Blockly.Blocks['reject'] = {
  init: function () {
    this.setColour(160)
    this.appendValueInput('REJECT')
      .appendField('reject返回')
    this.setPreviousStatement(true, null)
    this.setNextStatement(true, null)
    this.setInputsInline(false)
  }
}

Blockly.JavaScript['reject'] = function (block) {
  var value = Blockly.JavaScript.valueToCode(
    block,
    'REJECT',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  )
  return `reject(${value})\n`
}
